package com.ruoyi.accounting.validator;

import com.ruoyi.accounting.validator.annotation.EnumValidator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;

/**
 * 枚举值校验器
 */
public class EnumValueValidator implements ConstraintValidator<EnumValidator, Integer> {

    private Class<? extends Enum<?>> enumClass;

    @Override
    public void initialize(EnumValidator annotation) {
        this.enumClass = annotation.enumClass();
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (value == null) return true; // 可配合 @NotNull 控制

        try {
            Method method = enumClass.getMethod("isValidCode", Integer.class);
            Object result = method.invoke(null, value);
            return result instanceof Boolean && (Boolean) result;
        } catch (Exception e) {
            return false;
        }
    }
}
